package com.zwj.controller;

import com.zwj.common.enums.EnumErrorCode;
import com.zwj.common.utils.DateUtil;
import com.zwj.vo.BaseResp;
import com.zwj.vo.entity.Upload;
import com.zwj.vo.response.UploadListResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "上传接口")
@RestController
@RequestMapping("/upload/")
public class UploadController {
    private static final Logger LOGGER = LogManager.getLogger(UploadController.class);
    @Value("${upload.file.path}")
    private String uploadFilePath;
    @Value("${upload.domain}")
    private String uploadDomain;

    @ApiOperation(value = "文件上传", position = 1)
    @ApiImplicitParam(name = "files", value = "上传的文件", required = true, dataType = "MultipartFile.class", allowMultiple = true)
    @ResponseBody
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public BaseResp file(@RequestParam("files") MultipartFile[] fileArray) {
        BaseResp<UploadListResp> baseResp = new BaseResp<>();
        //非空判断
        if (fileArray == null || fileArray.length == 0) {
            return BaseResp.fail(EnumErrorCode.FILE_NOT_UPLOAD);
        }
        UploadListResp result = new UploadListResp();
        List<Upload> resultList = new ArrayList<>();

        //多文件循环操作
        for (MultipartFile multipartFile : fileArray) {
            //获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //获取文件后缀
            String[] split = originalFilename.split("\\.");
            //设置文件保存路径
            long currentTimeMS = DateUtil.getCurrentTimeMS();
            String saveFileName = originalFilename;
            //文件名尾加上时间戳，防止文件名重复
            if (split.length == 2) {
                saveFileName = split[0];
                saveFileName = saveFileName.concat("_").concat(String.valueOf(currentTimeMS)).concat(".").concat(split[1]);
            }
            //按照当前日期做文件夹分类
            String dateToStr = DateUtil.dateToStr(new Date(), "yyyy/MM");
            String completeFilePath = uploadFilePath.concat("/").concat(dateToStr).concat("/").concat(saveFileName);
            //创建File类
            File destFile = new File(completeFilePath);
            //上传操作
            try {
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                multipartFile.transferTo(destFile);
            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.error(originalFilename + "文件上传失败");
            }
            //封装文件信息
            Upload upload = new Upload();
            upload.setOriginalFilename(originalFilename);//文件名
            upload.setFileUrl(completeFilePath);//保存路径
            upload.setFileSize(multipartFile.getSize());//文件大小（字节）
            resultList.add(upload);
        }
        result.setResultList(resultList);
        result.setDomain(uploadDomain);
        baseResp.setData(result);
        return baseResp;
    }
}
